<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('mexico.fgAdjustment')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="barcodeSplitting" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-itemTwo" style="padding:0 0 10rpx 0">
						<text class="item-info-title">{{ $t('translationImage.warehouseSubordinate') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.warehouseCode" :placeholder="$t('pageTranslation.bringFromBarcode')" />
					</view>
					<view class="custom-card-itemTwo" style="padding: 16rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('warehousing.libraryBitCode') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-if="data.barcodeList.length > 0" v-model="data.locationCodes"
							:placeholder="$t('pageTranslation.bringFromBarcode')" />
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.locationCodes" v-else
							:placeholder="$t('warehousing.scanLocation')" @blur="data.focus = false" :focus="data.focus"
							@confirm="confirmLocation" @iconClick="iconClickLocation">
						</uni-easyinput>
					</view>
					<view v-if="data.isCapacityBool" class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeSeat') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-if="data.barcodeList.length > 0" v-model="data.locationId"
							:placeholder="$t('pageTranslation.bringFromBarcode')" />
						<storageBin ref="storageBinRef" v-model="data.locationId" v-else
							:ignoreLocationCode="data.ignoreLocationCode" class="gui-text-right"
							requestUrl="/api1/wms/warehouse/QueryLocation"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:requestParam="data.requestParam" @setClick="getClick"></storageBin>
					</view>
					<view v-else class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeSeat') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-if="data.barcodeList.length > 0" v-model="data.locationId"
							:placeholder="$t('pageTranslation.bringFromBarcode')" />
						<comboGrid ref="comboGridRef" v-model="data.locationId" :requestParam="data.requestParam"
							requestUrl="/api1/wms/warehouse/QueryLocation"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="locationCode"
							:column="data.columnRule.column" bindValue="locationName" @setClick="getRuleClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 16rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('distributedEnter.barcodeScan') }}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode"
							@focus="data.focus = false" :focus="!data.focus" type="search" @confirm="confirm"
							@iconClick="iconClick" :placeholder="$t('stockManage.pleaseScanCode')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title">{{ $t('translationImage.currentLocation') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.currentLocationCode" :placeholder="$t('pageTranslation.bringFromBarcode')" />
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title">{{ $t('mexico.destinationPoint') }}：</text>
						<input disabled class="uni-mt-5" type="number" style="margin: 8rpx 0;text-align: right;"
							v-model="data.pointPosition" />
						<!-- <comboGrid ref="comboGridRef" v-model="data.pointPosition" :requestParam="data.requestParamPosition"
							requestUrl="/api1/wms/point/GetLocationPoint"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="dianwei"
							:column="data.columnPosition.column" bindValue="locationName" @setClick="getRuleClick">
						</comboGrid> -->
					</view>
					<view class="custom-card-itemTwo" style="padding: 16rpx 0">
						<text class="item-info-title">{{ $t('mexico.pointsNumber') }}：</text>
						<input disabled class="uni-mt-5" type="number" style="margin: 8rpx 0;text-align: right;"
							v-model="data.positionNumber" />
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCoded') }}：
									</text>
									{{ data.scanInfo.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：
									</text>
									{{ data.scanInfo.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：
									</text>
									{{ data.scanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：
									</text>
									{{ data.scanInfo.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty') }}：
										</text>
										{{ data.scanInfo.currentQty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：
										</text>
										{{ data.scanInfo.unit }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">{{ $t('calendar.submit')
						}}
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import { DEFAULT_WAREHOUSECODE, DEFAULT_WAREHOUSEID } from '@/constant/index.js'
import { getDataDictionaryFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import {
	selectWmsBarcodeInfoWms, checkLocation, getLocationPoint,
	adjustBarcodeLocation, getIOTUsedLocation, setLocationLockStatus, setLocationLockStatusBatch, VerifyBarcode
} from '@/api/api.js'
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

components: {
	storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)
let store = useStore();
const navHeight = computed(() => {
	return store.state.navHeight
})
const { scan } = pdaScan()

let data = reactive({
	isCapacityBool: true,// 是否带容量 默认为false
	msgType: 'warn',
	value: ['0'],
	warehouseCode: 'FG',// 设置的默认仓库
	barcode: '', //条码
	barcodeList: [],//条码数组
	warehouseName: '', //所属仓库,
	currentLocationCode: '', //当前库位
	// objectiveSeat:'',//目的库位
	scanInfo: undefined,
	warehouseId: null,
	ignoreLocationCode: [], //前端算满的库位
	scanInfo: {},// 当前扫码
	locationId: '',//目的库位id
	requestParam: {
		warehouseId: 0,// 设置的默认仓库
		warehouseCode: 'FG', // 设置的默认仓库
		warehouseName: '',
		locationCode: '',
		locationName: '',
		locationTypeCode: '',
		locationTypeName: '',
		forbiddenStatus: '',
		areaCode: ''
	},
	columnRule: {
		column: [{
			label: t('distributedOut.location'),
			name: "locationCode",
		}]
	},
	locationUseList: [],
	requestParamPosition: { //点位获取
		barCode: '',// 条码
		locationCode: '', // 库位
	},
	columnPosition: {
		column: [{
			label: t('mexico.destinationPoint'),
			name: "locationCode",
		}]
	},
	locationName: '',// 选中库位
	locationCodes: '',
	currentLocationInfo: {},
	focus: true,
	pointPosition: '',
	positionNumber: null,
	whichTotal: null,
	lockCode: '',
})

onShow(async () => {
	// data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	// data.requestParam.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	// if (!data.warehouseCode.length) {
	// 	alertDialogOpen()
	// }
})
onMounted(() => {
	uni.$on('scancodedate', (itme) => {
		// console.log('获取到的code：' + itme.code, data.focus)
		if (data.focus) {
			getCodeLocation(itme.code, 'pda')
		}
		if (data.focus == false) {
			getCode(itme.code, 'pda')
		}
	})

})

// 计算库位逻辑
const calculateLocationCode = (newVal) => {
	let tepData = toRaw(newVal)
	if (!tepData.length) {
		data.scanInfo = undefined
		data.warehouseName = ''
		data.currentLocationCode = ''
	}
	// 计算点位数量
	data.positionNumber = data.whichTotal - tepData.length // 点位数量

	if (!data.scanInfo && tepData.length) {
		data.scanInfo = tepData[0]
		data.warehouseName = tepData[0].warehouseName
		data.currentLocationCode = tepData[0].locationCode
	}
	// 先清空,后续追加
	data.locationUseList.forEach(l => {
		l.barcodeList = []
	})
	// 追加
	tepData.forEach(x => {
		data.locationUseList.forEach(k => {
			if (x.locationId == k.locationCode) {
				k.barcodeList.push(x.barcode)
				k.surplusCapacity = k.currentCapacity - k.barcodeList.length
			}
		})
	})
	if (!data.isCapacityBool) return
	//算满库位变量置空
	data.ignoreLocationCode = []
	// 把前端预算容量算出为0的库位抽出
	data.locationUseList.forEach(x => {
		console.log(x)
		if (x.surplusCapacity == 0) {
			data.ignoreLocationCode.push(x.locationCode)
		}
	})
}

data.barcodeList = computed(() => {
	return store.state.fgAdjustmentList
})

//把扫描条码变为物料集合的二维数组
watch(() => data.barcodeList, (newVal, oldVal) => {
	calculateLocationCode(newVal)
}, {
	immediate: true,
	deep: true
});

// 用户调起相机扫码
const iconClickLocation = async (type) => {
	data.focus = true
	if (type === 'suffix') {
		let code = await scan()
		getCodeLocation(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirmLocation = () => {
	data.focus = true
	getCodeLocation(data.locationCodes, 'keydown')
}

// 获取code
const getCodeLocation = (code, type) => {
	// 如果不是第一次掃描庫位，就進行判斷解鎖庫位
	if (data.lockCode && data.lockCode != code) {
		setLocationLockStatus({
			locationCode: data.lockCode,
			locationLockStatus: 1
		}).then(res => {
			if (res.code == 0 && res.data) {
				data.lockCode = ''
				uni.showToast({
					title: t('mexico.libraryUnlocking'),
					icon: 'none',
				})
			} else {
				uni.showToast({ title: res.msg, icon: "none" });
			}
		})
	}
	let parme = [code]
	// 获取IOT库位运行情况
	getIOTUsedLocation(parme).then(res => {
		console.log(res)
		if (res.code == 0) {
			if (res.data[0].isUsed) {
				uni.showToast({
					title: t('mexico.locationNotUsed'),
					icon: 'none',
				})
				return
			} else {
				// 锁定库位
				setLocationLockStatus({
					locationCode: code,
					locationLockStatus: 0
				}).then(res => {
					if (res.code == 0 && res.data) {
						data.lockCode = code
						uni.showToast({
							title: t('mexico.successfullyCode'),
							icon: 'none',
						})
					} else {
						uni.showToast({ title: res.msg, icon: "none" });
					}
				})
			}
		}
	})
	data.locationCodes = code
	var parmes = {
		size: 99999,
		current: 1,
		warehouseid: 0,
		warehouseCode: data.warehouseCode,
		LocationCode: code,
	}
	checkLocation(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品库内调整'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			data.currentLocationInfo = res.data.records[0].wmsLocation;
			data.locationId = res.data.records[0].wmsLocation.locationCode;
			data.locationName = res.data.records[0].wmsLocation.locationCode
			data.requestParamPosition.locationCode = res.data.records[0].wmsLocation.locationCode
		}
		else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

// 获取选中的库位id
const getClick = (x) => {
	data.currentLocationInfo = x;
	data.locationId = x.locationCode;
	data.locationName = x.locationName
	data.locationCodes = x.locationCode;
}
// 获取选中的库位id
const getRuleClick = (x) => {
	data.currentLocationInfo = x;
	data.locationId = x.locationCode;
	data.locationName = x.locationName
}

// 用户点击扫码图标 扫描条码
const iconClick = async (type) => {
	data.focus = false
	if (type === 'suffix') {
		let code = await scan()
		if (!data.focus) {
			getCode(code, 'scan2')
		}
	}
}
// 用户点击搜索
const confirm = () => {
	data.focus = false
	if (!data.focus) {
		getCode(data.barcode, 'keydown')
	}
}

// 获取code
const getCode = (code, type) => {
	//首先验证条码是否有用
	console.log(data.barcodeList.length)
	let arr = []
	if (data.barcodeList.length > 0) {
		data.barcodeList.forEach(x => {
			arr.push(x.barcode)
		})
	}
	arr.push(code)
	VerifyBarcode({
		barCodes: arr
	}).then(res => {
		if (res.code != 0) {
			uni.showToast({
				title: res.msg,
				icon: 'error',
				duration: 5000
			})
			return;
		}
		else {
			data.barcode = code
			console.log(code, '---code---')
			// 判断这个托盘本次有没有绑定过
			console.log(data.barcodeList, 'data.barcodeList')
			if (!data.locationId) {
				uni.showToast({
					title: t('pageTranslation.plsChooseDestination'),
					icon: 'none'
				})
				return
			}
			let isBind = data.barcodeList.some(x => x.barcode == code);
			if (isBind) {
				uni.showToast({
					title: t('JsInternational.scanned'),
					icon: 'none'
				})
				return
			}
			// 判断当前用户选择的库位有没有容量
			if (data.pointPosition && data.positionNumber <= 0) {
				uni.showToast({
					title: t('mexico.pointsNoSubmit'),
					icon: 'none'
				})
				return
			}
			if (!code) {
				uni.showToast({
					title: t('stockManage.pleaseScanCode'),
					icon: 'none'
				})
				return
			}
			data.scanValue = code
			let parmes = {
				// isSp:0,
				barcode: code,
				barcodeTypeCode: null,
				locationCode: null,
				materialCode: null,
				materialName: null,
				current: 1,
				size: 99999
			}
			selectWmsBarcodeInfoWms(parmes).then(res => {
				try {
					let inputParameter = JSON.stringify(parmes)
					let returnParameter = JSON.stringify(res)
					let operationPicture = '成品库内调整'
					let callInterface = res.rquestUrl
					let opertionParmes = {
						inputParameter,
						returnParameter,
						operationPicture,
						callInterface,
						responseCode: res.code,//返回状态
						errorMessage: res.msg,//错误信息
						isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
						operationType: OPERATION_SCAN,
						module: 'WMS',
						source: "PDA",
					}
					basPdaOperationLogFn(opertionParmes)
				} catch (error) {
				}
				console.log(res)
				if (res.code == 0) {
					if (res.data.locationCode == data.locationId) {
						uni.showToast({
							title: t('JsInternational.locationSame'),
							icon: 'none'
						})
						return
					}
					if (res.data.records[0].warehouseCode != data.warehouseCode) {
						uni.showToast({
							title: t('mexico.scanFGBelong'),
							icon: 'none'
						})
						data.barcode = ''
						return
					}
					data.scanInfo = res.data.records[0]
					getLocationPoint({
						locationCode: data.locationId,
						barCode: code
					}).then(res => {
						if (res.code == 0) {
							if (data.pointPosition && data.pointPosition === res.data[0].whichNumber) {

							} else {
								data.whichTotal = res.data[0].availablenumber
								data.pointPosition = res.data[0].whichNumber
								data.positionNumber = res.data[0].availablenumber
								data.scanInfo.locationPointId = res.data[0].id
							}
						}
					})
					data.scanInfo.goaLlocationId = data.currentLocationInfo.id
					data.scanInfo.goalWarehouseCode = data.requestParam.warehouseCode
					data.scanInfo.goalLocationCode = data.currentLocationInfo.locationCode
					data.scanInfo.goalLocationName = data.currentLocationInfo.locationName
					data.warehouseName = res.data.records[0].warehouseName
					data.currentLocationCode = res.data.records[0].locationCode
					judgeBarcode()
				} else {
					uni.showToast({ title: res.msg, icon: "none" });
				}
			})


		}

	});

}

// 判断 Barcode
const judgeBarcode = () => {
	let isTrue = data.locationUseList.some(x => x.locationCode === data.locationId)
	if (!isTrue) {
		data.locationUseList.push({
			locationCode: data.currentLocationInfo.locationCode, //库位code
			surplusCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端告诉前端容量
			barcodeList: [], //当前库位本次扫描绑定的barcode条码集合
			currentCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
		})
	}
	store.commit('addFGAdjustmentList', data.scanInfo)
}

// 提交操作
const handelCommit = () => {
	if (!data.barcodeList.length) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	let tepData = toRaw(data.barcodeList)
	let parmes = {
		barcodeAdjustLocations: []
	}
	tepData.forEach(x => {
		console.log(x)
		parmes.barcodeAdjustLocations.push({
			barcodeId: x.id,// 条码的id
			descLocationCode: x.goalLocationCode,//库位code
			locationPointId: x.locationPointId,//点位id
			descLocationId: x.goaLlocationId,// 库位id
			barcode: x.barcode,
		})
	});
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	adjustBarcodeLocation(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品库内调整'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			//删除已提交的数据
			data.barcode = '' //置空当前条码
			data.locationCodes = ''
			data.locationId = ''
			data.currentLocationCode = ''
			data.pointPosition = ''
			data.positionNumber = ''
			data.scanInfo = undefined
			store.commit('reactFGAdjustmentList')
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})

}

//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/barcodeManagement/fgAdjustmentRecord'
	})
}

// 右侧返回
const clickLeftBack = () => {
	navBackCheck()
}

const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	// 返回的時候解鎖所有未提交的庫位
	let arr = []
	data.barcodeList.forEach(item => {
		arr.push({
			locationCode: item.goalLocationCode,
			locationLockStatus: 1
		})
	})
	setLocationLockStatusBatch(arr).then(res => {
		if (res.code == 0 && res.data) {
			data.lockCode = ''
			uni.showToast({
				title: t('mexico.libraryUnlocking'),
				icon: 'none',
			})
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('reactFGAdjustmentList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
	return true
}
</script>
<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>
